﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CPPEI.Web.Api
{
    public static class ActionEntry
    {
        public static void ProcessRequest(HttpContext context)
        {
            SysParameters sysParameters = GetParameter(context.Request);
            IAction action = ActionFactory.GetAction(sysParameters);
            if (action != null)
            {
                ActionResult result = action.Execute(context.Request, sysParameters);

                IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.NullValueHandling = NullValueHandling.Ignore;
                settings.Converters.Add(timeFormat);

                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result, Formatting.Indented, settings));
            }
        }


        private static SysParameters GetParameter(HttpRequest request)
        {
            SysParameters parameters = new SysParameters();
            parameters.Scenario = request.QueryString["sys:sno"];

            parameters.Command = request.QueryString["sys:cmd"];
            if (string.IsNullOrEmpty(parameters.Command))
            {
                parameters.Command = request.Form["sys:cmd"];
            }

            parameters.Version = request.QueryString["sys:ver"];
            parameters.Token = request.QueryString["sys:token"];
            if (string.IsNullOrEmpty(parameters.Token))
            {
                parameters.Token = request.Form["sys:token"];
            }

            return parameters;
        }
    }
}
